import 'package:flutter/material.dart';
import '../model/health_record.dart';
import '../model/reminder.dart';
import '../service/database_service.dart';
import 'base_record_dialog.dart';

class AddMedicineRecordDialog extends BaseRecordDialog {
  const AddMedicineRecordDialog({Key? key, required String babyId})
    : super(key: key, babyId: babyId);

  @override
  _AddMedicineRecordDialogState createState() =>
      _AddMedicineRecordDialogState();
}

class _AddMedicineRecordDialogState
    extends BaseRecordDialogState<AddMedicineRecordDialog> {
  final _nameController = TextEditingController();
  final _doseController = TextEditingController();
  String _unit = 'ml'; // 默认单位
  bool _isScheduled = false;
  TimeOfDay? _nextDoseTime;

  @override
  void dispose() {
    _nameController.dispose();
    _doseController.dispose();
    super.dispose();
  }

  @override
  String getDialogTitle() => '记录用药';

  @override
  Widget buildCustomContent(BuildContext context) {
    return Column(
      children: [
        TextField(
          controller: _nameController,
          decoration: InputDecoration(
            labelText: '药品名称',
            border: OutlineInputBorder(),
          ),
        ),
        SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              flex: 2,
              child: TextField(
                controller: _doseController,
                decoration: InputDecoration(
                  labelText: '剂量',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
              ),
            ),
            SizedBox(width: 8),
            Expanded(
              flex: 1,
              child: DropdownButtonFormField<String>(
                value: _unit,
                items:
                    ['ml', 'mg', '片', '滴'].map((unit) {
                      return DropdownMenuItem(value: unit, child: Text(unit));
                    }).toList(),
                onChanged: (value) {
                  setState(() => _unit = value!);
                },
              ),
            ),
          ],
        ),
        SwitchListTile(
          title: Text('需要定时提醒'),
          value: _isScheduled,
          onChanged: (value) {
            setState(() => _isScheduled = value);
          },
        ),
        if (_isScheduled) ...[
          ListTile(
            title: Text('下次用药时间'),
            trailing: TextButton(
              child: Text(_nextDoseTime?.format(context) ?? '选择时间'),
              onPressed: () async {
                final time = await showTimePicker(
                  context: context,
                  initialTime: TimeOfDay.now(),
                );
                if (time != null) {
                  setState(() => _nextDoseTime = time);
                }
              },
            ),
          ),
        ],
      ],
    );
  }

  @override
  Future<void> saveRecord(BuildContext context) async {
    if (_nameController.text.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('请输入药品名称')));
      return;
    }

    if (_doseController.text.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('请输入剂量')));
      return;
    }

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.medicine,
          timestamp: selectedDateTime,
          data: {
            'name': _nameController.text,
            'dose': _doseController.text,
            'unit': _unit,
            'isScheduled': _isScheduled,
            'nextDoseTime': _nextDoseTime?.format(context),
            'notes': notes,
          },
        ),
      );

      // 如果设置了提醒，创建提醒
      if (_isScheduled && _nextDoseTime != null) {
        // await DatabaseService().addReminder(
        //   Reminder(
        //     id: 0,
        //     babyId: widget.babyId,
        //     title: '用药提醒：${_nameController.text}',
        //     type:ReminderType.medicine,
        //     scheduleTime: selectedDateTime
        //   ),
        // );
      }

      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
    }
  }
}
